package com.UMLife.me.model;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

public class Communication implements Runnable{
	private  String character ;
	HttpConnection httpConnection = null;       //无可见性修饰符，只包内可见
	DataOutputStream output = null;
	DataInputStream input = null;
	private String msg;
	private int nb;                               //nb为服务器返回的msg个数1或4
	private String[] respone=new String[4];       
	private boolean dealing=true;
	private String url = "http://localhost:8084/mobileresearchstar//servlet/Servlet";

	/**
	 * 建立与服务器的连接
	 */
	
	public void post()
	{
		//TODO
		try{
			byte data[]=msg.getBytes("GB2312");
			httpConnection = (HttpConnection)Connector.open(url);
			httpConnection.setRequestMethod(HttpConnection.POST);
			output = httpConnection.openDataOutputStream();
			for(int i=0;i<=data.length;i++)
			{
				output.write((byte)data[i]);             //将数据上传到服务器
				for(int j=0;j<=nb;j++)
				respone[j]=readRespone(httpConnection);       //从服务器读取数据
			} 
			if(output != null)output.close();
			if(input != null)input.close();
			if(httpConnection != null)httpConnection.close();
     
		}catch(Exception e){
			e.printStackTrace();
		}

	}
	
	
	/***
	 * 获取服务器返回值
	 * */
	private String readRespone(HttpConnection httpConnection) throws IOException
	{    //TODO
		//httpConnection = (HttpConnection)Connector.open(url);
		int status=httpConnection.getResponseCode();
		if(status==HttpConnection.HTTP_OK)
		{  input = httpConnection.openDataInputStream();
		   int len=(int)httpConnection.getLength();
		   if(len>0)
		   {
			   int actual=0;
			   int bytesread=0;
			   byte[] data = new byte[len];
			   while(bytesread!=len&&actual!=-1)
			   {
				   actual=input.read(data,bytesread,len-bytesread);
		            bytesread += actual;
			   }
			   character=process(data);         //转换为String型
		   }
		  
		}
		return character;
	}
	
  /***
   * 将Gb2312编码转换为String型
   * */
	private String  process(byte[] data)
	{   //TODO
	    String str= "";
	    try{
	        str= new String(data,"GB2312");
	    }
	    catch(Exception e)
	    {
	    	e.printStackTrace();
	    }
		return str;
	}
	
	
	/***
	 * 向服务器上传msg
	 * */
	public void Setmsg(String msg)
	{   //TODO
		this.msg=msg;
	}
	
	/****
	 * 设置获取的次数
	 * */
	public void SetNb(int nb)
	{
		this.nb=nb;
	}
	
	/****
	 * 获取服务器返回的第1个message值
	 * */
    public String Getrespone1()
    {
    	return this.respone[0];
    }
    
    /****
	 * 获取服务器返回的第2个message值
	 * */
    public String Getrespone2()
    {
    	return this.respone[1];
    }
    
    /****
	 * 获取服务器返回的第3个message值
	 * */
    public String Getrespone3()
    {
    	return this.respone[2];
    }
    
    /****
	 * 获取服务器返回的第4个message值
	 * */
    public String Getrespone4()
    {
    	return this.respone[4];
    }
    
    
    
    /***
     * 线程
     * */
    public synchronized void run() 
    {
    	//TODO
        while (dealing) 
        {
       	 
                  try { wait(50); }//线程等待
                  
                   catch (InterruptedException ie)
                       {
                	   ie.printStackTrace();
                	   }
                   if (dealing) post();
        		}
   		}
    
    /***
     * 有点问题，待修改
     * */
   		public synchronized void deal() 
   		{
                notify();//唤醒线程
   		}

	/**
	* 分割字符串，原理：检测字符串中的分割字符串，然后取子串
	* @param original 需要分割的字符串
	* @paran regex 分割字符串
	* @return 分割后生成的字符串数组
	*/
	public String[] split(String original,String regex)
	 {   //TODO
		//取子串的起始位置
		 int startIndex = 0;
		//将结果数据先放入Vector中
		 Vector v=new Vector();
		  //返回的结果字符串数组
		String[] str = null;
		//存储取子串时起始位置
		int index = 0;
		
		//获得匹配子串的位置
		startIndex = original.indexOf(regex); 
		//System.out.println("0" + startIndex); 
			//如果起始字符串的位置小于字符串的长度，则证明没有取到字符串末尾。
		//-1代表取到了末尾
		while(startIndex < original.length() && startIndex != -1)
		{
		String temp = original.substring(index,startIndex);
		//System.out.println(" " + startIndex);
		//取子串
		v.addElement(temp);
		
		//设置取子串的起始位置
		index = startIndex + regex.length();
		
		//获得匹配子串的位置
		startIndex = original.indexOf(regex,startIndex + regex.length());
		}
		
		//取结束的子串
		v.addElement(original.substring(index + 1 - regex.length()));
		//将Vector对象转换成数组
		str = new String[v.size()];
		for(int i=0;i<v.size();i++)
		{
		str[i] = (String)v.elementAt(i);
		}
		
		//返回生成的数组
		return str;
	 }
}
